<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="handleDialogClose">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="素材名" prop="materialName">
      <el-input v-model="dataForm.materialName" placeholder=""></el-input>
    </el-form-item>
    <el-form-item label="文件大小" prop="materialFileSize">
      <el-input v-model="dataForm.materialFileSize" placeholder="上传图片自动识别" disabled></el-input>
    </el-form-item>
    <el-form-item label="宽(px)" prop="materialWidth">
      <el-input v-model="dataForm.materialWidth" placeholder="上传图片自动识别" disabled></el-input>
    </el-form-item>
    <el-form-item label="高(px)" prop="materialHeight">
      <el-input v-model="dataForm.materialHeight" placeholder="上传图片自动识别" disabled></el-input>
    </el-form-item>
    <el-form-item label="标签" prop="materialLabel">
      <el-input v-model="dataForm.materialLabel" placeholder=""></el-input>
    </el-form-item>
    <el-form-item label="分类" prop="materialCategoryCode">
      <el-cascader
        v-model="selectedCategory"
        :options="categoryTree"
        :props="cascaderProps"
        placeholder="请选择分类"
        clearable
        style="width: 100%">
      </el-cascader>
    </el-form-item>
    <el-form-item label="素材图片" prop="materialImageUrl">
        <el-upload
          ref="upfileload"
          class="upload-demo"
          :data="dataObj"
          :action="dataObj.host"
          :auto-upload=false
          :before-upload="getImagePolicy"
          :on-success="handleImageUploadSuccess"
          list-type="picture">
          <el-button size="small" type="primary">选择图片</el-button>
          <div slot="tip" class="el-upload__tip">可上传任意格式图片文件</div>
        </el-upload>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="clearData">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        makeSure: false,
        dataForm: {
          id: 0,
          materialCode: '',
          materialName: '',
          materialFileSize: '',
          materialWidth: '',
          materialHeight: '',
          materialLabel: '',
          materialCategoryCode: '',
          materialCategoryFirst: '',
          materialCategorySecond: '',
          materialImageUrl: '',
        },
        dataObj: {
          policy: '',
          signature: '',
          OSSAccessKeyId: '',
          key: '',
          dir: '',
          host: '',
          expire: ''
        },
        categoryTree: [],
        selectedCategory: [],
        cascaderProps: {
          value: 'categoryCode',
          label: 'categoryName',
          children: 'children',
          expandTrigger: 'hover'
        },
        dataRule: {
          materialName: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          materialFileSize: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          materialWidth: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          materialHeight: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          materialLabel: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          materialCategoryCode: [
            { required: true, message: '请选择分类', trigger: 'blur' }
          ],
          materialImageUrl: [
            { required: true, message: '请上传素材图片', trigger: 'change' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.getCategoryList()
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/material/material/queryWormholeGalaxyMaterial`),
              method: 'post',
              data: this.$http.adornData({
                "id":id
              })
            }).then(({data}) => {
              if (data) {
                this.dataForm.gmtCreate = data.wmhGalaxyMaterial.gmtCreate
                this.dataForm.materialCode = data.wmhGalaxyMaterial.materialCode
                this.dataForm.materialName = data.wmhGalaxyMaterial.materialName
                this.dataForm.materialFileSize = data.wmhGalaxyMaterial.materialFileSize
                this.dataForm.materialWidth = data.wmhGalaxyMaterial.materialWidth
                this.dataForm.materialHeight = data.wmhGalaxyMaterial.materialHeight
                this.dataForm.materialUseRate = data.wmhGalaxyMaterial.materialUseRate
                this.dataForm.materialLabel = data.wmhGalaxyMaterial.materialLabel
                this.dataForm.materialCategoryCode = data.wmhGalaxyMaterial.materialCategoryCode
                this.dataForm.materialItemCode = data.wmhGalaxyMaterial.materialItemCode
                this.dataForm.materialImageUrl = data.wmhGalaxyMaterial.materialImageUrl
                // 设置分类选择器的值
                if (this.dataForm.materialCategoryCode) {
                  this.setCategoryValue(this.dataForm.materialCategoryCode)
                }
              }
            })
          }
        })
      },
      // 获取分类列表
      getCategoryList() {
        this.$http({
          url: this.$http.adornUrl('/category/category/queryWormholeGalaxyCategoryList'),
          method: 'post',
          data: this.$http.adornData({
            isPage: false,
          })
        }).then(({ data }) => {
          if (data && data.success) {
            this.categoryTree = data.data
          } else {
            this.categoryTree = []
          }
        })
      },
      // 设置分类选择器的值
      setCategoryValue(categoryCode) {
        const findCategoryPath = (categories, code) => {
          for (const category of categories) {
            if (category.categoryCode === code) {
              return [code];
            }
            if (category.children) {
              const path = findCategoryPath(category.children, code);
              if (path) {
                return [category.categoryCode, ...path];
              }
            }
          }
          return null;
        };

        const path = findCategoryPath(this.categoryTree, categoryCode);
        if (path) {
          this.selectedCategory = path;
        }
      },

      // 表单提交
      dataFormSubmit () {
        // 从级联选择器中获取选中的分类code
        if (this.selectedCategory && this.selectedCategory.length > 0) {
          this.dataForm.materialCategoryCode = this.selectedCategory[this.selectedCategory.length - 1];

          // 根据分类层级设置不同的分类字段
          if (this.selectedCategory.length === 1) {
            // 只有一级分类
            this.dataForm.materialCategoryFirst = this.selectedCategory[0];
            this.dataForm.materialCategorySecond = this.selectedCategory[0];
          } else if (this.selectedCategory.length === 2) {
            // 只有两级分类
            this.dataForm.materialCategoryFirst = this.selectedCategory[0];
            this.dataForm.materialCategorySecond = this.selectedCategory[1];
          } else if (this.selectedCategory.length >= 3) {
            // 有三级或以上分类
            this.dataForm.materialCategoryFirst = this.selectedCategory[0];
            this.dataForm.materialCategorySecond = this.selectedCategory[1];
          }
        } else {
          this.dataForm.materialCategoryCode = '';
          this.dataForm.materialCategoryFirst = '';
          this.dataForm.materialCategorySecond = '';
        }

        this.makeSure = false;
        this.$refs.upfileload.submit()

        // 使用轮询方式等待上传完成后再提交表单
        const checkUpload = setInterval(() => {
          if (this.makeSure) {
            clearInterval(checkUpload);
            this.submitFormData();
          }
        }, 1000);

        // 设置超时时间，避免无限等待
        setTimeout(() => {
          clearInterval(checkUpload);
          if (!this.makeSure) {
            this.$message.warning('上传超时，请重新尝试');
          }
        }, 10000);
      },

      // 提交表单数据
      submitFormData() {
        console.log('提交表单数据:', this.makeSure)
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/material/material/${!this.dataForm.id ? 'createWormholeGalaxyMaterial' : 'updateWormholeGalaxyMaterial'}`),
              method: 'post',
              data: this.$http.adornData({
                'materialCode': this.dataForm.materialCode,
                'materialName': this.dataForm.materialName,
                'materialFileSize': this.dataForm.materialFileSize,
                'materialWidth': this.dataForm.materialWidth,
                'materialHeight': this.dataForm.materialHeight,
                'materialLabel': this.dataForm.materialLabel,
                'materialCategoryCode': this.dataForm.materialCategoryCode,
                'materialCategoryFirst': this.dataForm.materialCategoryFirst,
                'materialCategorySecond': this.dataForm.materialCategorySecond,
                'materialImageUrl': this.dataForm.materialImageUrl,
              })
            }).then(({data}) => {
              if (data && data.success) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.clearData()
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
                this.clearData()
              }
            })
          }
        })
      },

      // 获取上传策略
      getImagePolicy(file) {
        // 移除了文件类型和大小的限制检查
        return this.$http({
          url: this.$http.adornUrl('/oss/uploadByPolicy'),
          method: 'post',
          data: this.$http.adornData({
            "path": 'material',
          })
        }).then(({data}) => {
          if (data) {
            this.dataObj.key = data.data.dir + file.name
            this.dataObj.policy = data.data.policy
            this.dataObj.signature = data.data.signature
            this.dataObj.OSSAccessKeyId = data.data.accessKeyId
            this.dataObj.dir = data.data.dir
            this.dataObj.host = data.data.host
            this.dataObj.expire = data.data.expire

            // 直接设置文件大小到表单 (KB)
            const fileSizeKB = (file.size / 1024).toFixed(1) + ' KB';
            this.$set(this.dataForm, 'materialFileSize', fileSizeKB);

            // 获取图片尺寸
            const reader = new FileReader();
            reader.onload = (e) => {
              const img = new Image();
              img.onload = () => {
                // 设置图片尺寸到表单
                this.$set(this.dataForm, 'materialWidth', img.width.toString());
                this.$set(this.dataForm, 'materialHeight', img.height.toString());

                // 手动触发验证，确保所有字段通过验证
                this.$nextTick(() => {
                  this.$refs['dataForm'].validateField('materialFileSize');
                  this.$refs['dataForm'].validateField('materialWidth');
                  this.$refs['dataForm'].validateField('materialHeight');
                });
              };
              img.src = e.target.result;
            };
            reader.readAsDataURL(file);
          }
        })
      },
      // 图片上传成功处理
      handleImageUploadSuccess(response, file, fileList) {
          this.dataForm.materialImageUrl = this.dataObj.host+"/"+this.dataObj.key
          this.makeSure = true
          this.$message.success('图片上传成功！');
      },
      // 清除表单数据
      clearData() {
        // 重置表单数据
        this.dataForm = {
          id: 0,
          materialCode: '',
          materialName: '',
          materialFileSize: '',
          materialWidth: '',
          materialHeight: '',
          materialLabel: '',
          materialCategoryCode: '',
          materialCategoryFirst: '',
          materialCategorySecond: '',
          materialImageUrl: '',
        }

        // 重置级联选择器
        this.selectedCategory = []

        // 清空上传文件列表
        if (this.$refs.upfileload) {
          this.$refs.upfileload.clearFiles()
        }

        // 关闭对话框
        this.visible = false
      },
      // 处理对话框关闭事件
      handleDialogClose() {
        this.clearData()
      }
    }
  }
</script>

<style scoped>
.upload-demo {
  width: 100%;
}

.preview-image img {
  max-width: 100%;
  height: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
}
</style>
